/**
 * Copyright (c) 2020 kedacom
 * OpenATC is licensed under Mulan PSL v2.
 * You can use this software according to the terms and conditions of the Mulan PSL v2.
 * You may obtain a copy of Mulan PSL v2 at:
 * http://license.coscl.org.cn/MulanPSL2
 * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
 * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
 * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
 * See the Mulan PSL v2 for more details.
 **/
<template>
  <div class="routeOptimize">
    <Messagebox :visible="messageboxVisible" :text="$t('openatc.greenwaveoptimize.clearWarn')" @cancle="cancle" @ok="ok"/>
    <div class="funcs" v-show="isShowOperation">
      <div class="title" style="display:none;">{{this.menuRouteOptimize ? this.menuRouteOptimize : $t('openatc.main.routeOptimize')}}</div>
      <div class="btnGroup">
        <div class="btn-left" :style="{ zIndex: zIndexObj.addZIndex }">
            <div class="filter">
              <el-input
                v-model="filter"
                :placeholder="$t('openatc.common.searchplaceholder')"
                clearable
              >
                <el-button
                  slot="append"
                  @click="refresh()"
                  icon="el-icon-search"
                ></el-button>
              </el-input>
            </div>
            <el-button type="text" icon="el-icon-plus" slot="reference" class="btn" @click="onAddButtonClick" ref="addbtn">
              {{ $t("openatc.common.add") }}
            </el-button>
            <el-button type="text" icon="el-icon-edit" slot="reference" class="btn" style="margin-left:10px;" @click="onEditButtonClick" ref="addbtn">{{$t('openatc.common.edit')}}</el-button>
            <el-button type="text" icon="el-icon-refresh" slot="reference" class="btn" style="margin-left:10px;" @click="onClearButtonClick" ref="addbtn">{{$t('openatc.common.clear')}}</el-button>
            <el-button type="text" icon="el-icon-delete" slot="reference" class="btn" @click="onDeleteButtonClick" ref="addbtn">{{$t('openatc.common.delete')}}</el-button>
        </div>
        <div class="btn-right">
          <div style="display:flex;justify-content:center;">
            <el-button type="primary" size="medium" @click="onChartClick">{{$t('openatc.greenwaveoptimize.spaceGraph')}}</el-button>
            <el-button type="primary" size="medium" @click="onGenerateClick">{{$t('openatc.greenwaveoptimize.generate')}}</el-button>
            <el-button type="primary" size="medium" @click="onSaveClick">{{$t('openatc.common.save')}}</el-button>
            <el-button type="primary" size="medium" @click="onDownloadClick">{{$t('openatc.button.download')}}</el-button>
            <el-button type="primary" size="medium" @click="onExecuteClick">{{$t('openatc.greenwaveoptimize.executeTemply')}}</el-button>
          </div>
        </div>
      </div>
    </div>
    <el-container class="container">
      <el-aside width="180px">
        <PlanMenu :planData="planData"
        :zIndexObj="zIndexObj"
        :loading="loading"
        :isMenuDisabled="isMenuDisabled"
        ref="planMenu"
        @maskChange="maskChange"
        @chooseRoute="chooseRoute"
        @resetContentComponent="resetContentComponent"
        @editStart="editStart"
        @refresh="refresh"/>
      </el-aside>
      <el-main>
        <div class="compatibility" style="margin-top: -10PX;display: flex;justify-content: flex-end;">
          <el-checkbox v-model="compatibility" :true-label="1" :false-label="0">{{$t('openatc.greenwaveoptimize.compatibility')}}</el-checkbox>
        </div>
        <div class="timeDistanceChart" style="margin-top: -30PX;margin-bottom: 10PX;display: flex;flex-shrink: 0;" v-if="!isShowOperation">
          <TimeDistanceChart
              ref="rimeDistanceChart"
              :isShowPlanChart="isShowPlanChart"
              :isShowRealtimeChart="isShowRealtimeChart"
              :isShowTitle="isShowTitle"
            ></TimeDistanceChart>
        </div>
        <div class="main-container" style="border: 0px solid yellow;height: 90%;">
          <el-tabs v-model="editableTabsValue" type="card"  @edit="handleTabsEdit" :before-leave="beforeLeave" style="border: 0px solid yellow;height: 100%;" v-loading="mainLoading">
            <el-tab-pane
              :closable="true"
              :key="item.tabName"
              v-for="(item, index) in editableTabs"
              :label="item.title"
              :name="item.tabName"
            >
              <div class="panel-content" style="border: 0px solid yellow;height: 100%;">
                <div style="border: 0px solid red;height: 12%;">
                  <div class="route-filter-container" style="display:flex;">
                    <div class="filter">
                      <span class="header-span">{{$t('openatc.greenwaveoptimize.patternName')}}：</span>
                      <el-input
                          clearable
                          size="small"
                          v-model="item.title"
                          style="width:70%;"
                          @change="onConditionChange(item)"
                      />
                    </div>
                    <div class="filter">
                      <span class="header-span">{{$t('openatc.greenwaveoptimize.coordinationstrategy')}}：</span>
                      <el-select v-model="item.optstrategy"
                                style="width:70%;"
                                  @change="onOptstrategyChange"
                                :placeholder="$t('openatc.common.placeholder')"
                                size="small">
                        <el-option
                          v-for="item in optstrategyOptions"
                          :key="item.value"
                          :label="$t('openatc.greenwaveoptimize.optstrategyoption' + item.id)"
                          :value="item.value">
                        </el-option>
                      </el-select>
                    </div>
                    <div class="filter">
                      <span class="header-span">{{$t('openatc.greenwaveoptimize.coordinationdirection')}}：</span>
                      <el-select v-model="item.direction"
                                :placeholder="$t('openatc.common.placeholder')"
                                size="small"
                                style="width:70%;"
                                @change="onDirectionChange">
                        <el-option
                          v-for="dir in directionOptions"
                          :key="dir.value"
                          :label="$t('openatc.greenwaveoptimize.directionOption' + dir.id)"
                          :disabled="item.optstrategy != 'green' && dir.value === 'all'"
                          :value="dir.value">
                        </el-option>
                      </el-select>
                    </div>
                    <div class="filter" style="display: flex;justify-content: flex-end;border:0px solid red;">
                      <span class="header-span">{{$t('openatc.greenwaveoptimize.upspeed')}}：</span>
                      <el-input-number :controls="false"
                                      style="width:50%;"
                                      :min="0"
                                        size="small"
                                        @change="onUpspeedChange"
                                      v-model="item.upspeed"
                                      ></el-input-number>
                    </div>
                    <div class="filter" style="display: flex;justify-content: flex-end;border:0px solid red;">
                      <span class="header-span">{{$t('openatc.greenwaveoptimize.downspeed')}}：</span>
                      <el-input-number :controls="false"
                                      style="width:50%;"
                                      :min="0"
                                        size="small"
                                        @change="onDownspeedChange"
                                      v-model="item.downspeed"
                                      ></el-input-number>
                    </div>
                    <div class="filter">
                      <span class="header-span">{{$t('openatc.greenwaveoptimize.keyintersection')}}：</span>
                      <el-select v-model="item.keyintsid"
                                :placeholder="$t('openatc.common.placeholder')"
                                style="width:70%;"
                                @change="onIntersectionSelectChange(item.keyintsid, index)"
                                size="small">
                        <el-option
                          v-for="item in keyintsidOptions"
                          :key="item.value"
                          :label="item.label"
                          :value="item.value">
                        </el-option>
                      </el-select>
                    </div>
                    <div class="filter" v-show="!compatibility">
                      <span class="header-span">{{$t('openatc.greenwaveoptimize.period')}}：</span>
                      <template>
                        <el-time-select
                          style="width:35%;"
                          size="small"
                          v-model="item.plan.start"
                          :picker-options="{
                            start: '00:00',
                            step: '00:15',
                            end: '23:59'
                          }">
                        </el-time-select>
                        <el-time-select
                          style="width:35%;"
                          size="small"
                          v-model="item.plan.end"
                          :picker-options="{
                            start: '00:00',
                            step: '00:15',
                            end: '23:59',
                            minTime: item.plan.start
                          }">
                        </el-time-select>
                      </template>
                    </div>
                    <div class="filter" v-show="!compatibility">
                      <span class="header-span">{{$t('edge.date.month')}}：</span>
                      <el-select multiple
                                  v-model="item.month"
                                  style="width:70%;"
                                  :placeholder="$t('edge.common.select')"
                                  size="small"
                                  :collapse-tags="true"
                                  @change="handleMonth(item.month, index)"
                                  @visible-change="initOldOptions(item.month, $event)">
                        <el-option
                          v-for="item in months"
                          :key="item.label"
                          :label="item.label"
                          :value="item.value">
                        </el-option>
                      </el-select>
                    </div>
                    <div class="filter" v-show="!compatibility">
                      <span class="header-span">{{$t('edge.date.day') }}：</span>
                      <el-select multiple
                                  style="width:70%;"
                                  v-model="item.day"
                                  :placeholder="$t('edge.common.select')"
                                  size="small"
                                  :collapse-tags="true"
                                  @change="handleDay(item.day, index)"
                                  @visible-change="initOldOptions(item.day, $event)">
                        <el-option
                          v-for="item in days"
                          :key="item.label"
                          :label="item.label"
                          :value="item.value">
                        </el-option>
                      </el-select>
                    </div>
                    <div class="filter" v-show="!compatibility">
                      <span class="header-span">{{$t('edge.date.date') }}：</span>
                      <el-select  multiple
                                  style="width:70%;"
                                  :collapse-tags="true"
                                  v-model="item.date"
                                  :placeholder="$t('edge.common.select')"
                                  size="small"
                                  @change="handleDate(item.date, index)"
                                  @visible-change="initOldOptions(item.date, $event)">
                        <el-option
                          v-for="item in dates"
                          :key="item"
                          :label="item"
                          :value="item">
                        </el-option>
                      </el-select>
                    </div>
                  </div>
                </div>
                <div style="height: 88%;border: 0px solid green;" class="table-container">
                  <PatternTable ref="patterntable"
                                :optList="item.devs"
                                :routeDevs="route.devs"
                                @onNewPatternListChange="onNewPatternListChange"/>
                </div>
              </div>
            </el-tab-pane>
            <el-tab-pane key="add" name="add" :closable="false">
              <span slot="label" style="padding: 8px;font-size:20px;font-weight:bold;">
                  +
              </span>
            </el-tab-pane>
          </el-tabs>
        </div>
      </el-main>
    </el-container>
    <PlanContent
        :compatibility="compatibility"
        :schemeData="schemeData"
        :step="step"
        :zIndexObj="zIndexObj"
        :routeId="chooseId"
        ref="planContent"
        @emitLoading="emitLoading"
        @handlePlanChart="handlePlanChart"
        @handlePatternTable="handlePatternTable"
        @ErrorOcurrred='onErrorOcurrred'
        @resetContentComponent="resetContentComponent"/>
    <chartDialog ref="chartDialog" :routeId="chooseId"></chartDialog>
    <PlanExecute ref="planExecute" :compatibility="compatibility"></PlanExecute>
  </div>
</template>

<script>
import PlanMenu from './planMenu'
import PlanContent from './planContent'
import { GetAllRoute } from '../../api/route'
import chartDialog from './pattern/planChart/chartDialog'
import TimeDistanceChart from './pattern/planChart/timeDistanceChart.vue'
import { getMessageByCode } from '../../utils/responseMessage'
import PatternTable from './pattern/patternTable'
import dateObj from './utils.js'
import routeChart from './pattern/planChart/index'
import PlanExecute from './components/planExecute'
import { GetDeviceByIds } from '../../api/device.js'
import { SystemconfigApi } from '../../api/systemconfig.js'
import '../../mock/index.js'
import Messagebox from '../../components/MessageBox'

const { monthsModel, daysModelCh, daysModelEn, datesModel, monthsModelEn, datesModelEn } = dateObj
export default {
  name: 'GreenWaveOptimize',
  components: {
    TimeDistanceChart,
    routeChart,
    PatternTable,
    PlanMenu,
    PlanContent,
    chartDialog,
    PlanExecute,
    Messagebox
  },
  props: {
    routesList: {
      type: Array,
      default: () => []
    },
    isShowPlanChart: {
      type: Boolean,
      default: true
    },
    isShowRealtimeChart: {
      type: Boolean,
      default: false
    },
    isShowTitle: {
      type: Boolean,
      default: false
    },
    isShowOperation: {
      type: Boolean,
      default: true
    }
  },
  watch: {
    routesList: {
      handler: function (val) {
        this.$nextTick(() => {
          // console.log('routesList change')
          this.resetContentComponent()
        })
      },
      deep: true
    }
  },
  data () {
    return {
      mainLoading: false,
      compatibility: 1,
      filter: '',
      isMenuDisabled: false,
      menuRouteOptimize: '',
      defaultSpeed: 40,
      defaultDay: [0, 1, 2, 3, 4, 5, 6],
      defaultDate: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31],
      defaultMonth: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12],
      chartData: {},
      months: monthsModel,
      days: [],
      dates: datesModel,
      planData: [],
      schemeData: [],
      step: false, // 控制第二个蒙层是否可以显示
      zIndexObj: {
        // 由于“新增”“编辑”均有蒙层，因此需动态改变可点击按钮层级
        addZIndex: 98,
        editZIndex: 98
      },
      reset: false,
      activeName: 'first',
      chooseId: 0, // 选中的计划id
      loading: false,
      keyintsidOptions: [],
      directionOptions: [{
        value: 'up',
        label: this.$t('openatc.greenwaveoptimize.directionOption1'),
        id: '1'
      }, {
        value: 'down',
        label: this.$t('openatc.greenwaveoptimize.directionOption2'),
        id: '2'
      }, {
        value: 'all',
        label: this.$t('openatc.greenwaveoptimize.directionOption3'),
        id: '3'
      }],
      optstrategyOptions: [{
        value: 'green',
        label: this.$t('openatc.greenwaveoptimize.optstrategyoption1'),
        id: '1'
      }, {
        value: 'red',
        label: this.$t('openatc.greenwaveoptimize.optstrategyoption2'),
        id: '2'
      }, {
        value: 'motorcade-end',
        label: this.$t('openatc.greenwaveoptimize.optstrategyoption3'),
        id: '3'
      }, {
        value: 'dynamicGreen',
        label: this.$t('openatc.greenwaveoptimize.optstrategyoption4'),
        id: '4'
      }],
      editableTabsValue: '1',
      routePattern: {
        'id': 1,
        'optPatternList': []
      },
      defaultOptPattern: {
        'tabName': '1',
        'month': [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12],
        patternid: 1,
        'day': [0, 1, 2, 3, 4, 5, 6],
        'date': [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31],
        'plan': {
          'start': '08:00',
          'end': '09:30'
        },
        'optstrategy': 'green',
        'direction': 'up',
        'keyintsid': '',
        'upspeed': 40,
        'downspeed': 40,
        'devs': []
      },
      currentIndex: 0,
      editableTabs: [{
        title: this.$t('openatc.greenwaveoptimize.optimizePattern') + ' 1',
        tabName: '1',
        name: this.$t('openatc.greenwaveoptimize.optimizePattern') + ' 1',
        content: 'Tab 1 content',
        patternid: 1,
        'month': [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12],
        'day': [0, 1, 2, 3, 4, 5, 6],
        'date': [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31],
        'plan': {
          'start': '11:00',
          'end': '13:00'
        },
        'optstrategy': 'green',
        'direction': 'up',
        'keyintsid': '',
        'upspeed': 40,
        'downspeed': 40,
        'devs': []
      }],
      tabIndex: 1,
      messageboxVisible: false
    }
  },
  created () {
    this.resetTab()
    let lan = this.$i18n.locale
    if (lan === 'en') {
      this.days = daysModelEn
      this.dates = datesModelEn
      this.months = monthsModelEn
    }
    if (lan === 'zh') {
      this.days = daysModelCh
      this.dates = datesModel
      this.months = monthsModel
    }
    this.getMemu()
  },
  mounted () {
    this.getAllPlan()
  },
  methods: {
    emitLoading (val) {
      this.mainLoading = val
    },
    getMemu () {
      let reqData = {
        module: 'menu',
        isValid: true
      }
      SystemconfigApi.GetSystemconfigList(reqData).then((data) => {
        let res = data.data
        if (!res.success) {
          console.log('datas:' + res)
          throw new Error('getMemu error')
        } else {
          for (let config of data.data.data) {
            if (config['key'] === 'routeOptimize') {
              this.menuRouteOptimize = config['value']
            }
          }
        }
      })
    },
    check () {
      let res = true
      if (this.chooseId === 0) {
        this.$message({
          message: this.$t('openatc.dutyroute.nochooseplan'),
          type: 'warning'
        })
        res = false
      }
      return res
    },
    onAddButtonClick () {
      // this.chooseId = 0
      let palnContent = this.$refs.planContent
      if (palnContent) {
        palnContent.handleAdd(this.route)
      }
    },
    onEditButtonClick () {
      if (!this.check()) {
        return false
      }
      // let title = this.$t('openatc.greenwaveoptimize.sureToEdit')
      // let msg = this.$t('openatc.greenwaveoptimize.editWarn')
      // this.$confirm(msg, title, {
      //   confirmButtonText: this.$t('openatc.button.OK'),
      //   cancelButtonText: this.$t('openatc.button.Cancel'),
      //   type: 'warning'
      // }).then(() => {
      //   this.handleEditClick()
      // })
      this.handleEditClick()
    },
    onClearButtonClick () {
      if (!this.check()) {
        return false
      }
      this.messageboxVisible = true
    },
    cancle () {
      this.messageboxVisible = false
    },
    ok () {
      this.messageboxVisible = false
      this.handleClearClick()
    },
    handleClearClick () {
      let palnContent = this.$refs.planContent
      if (palnContent) {
        palnContent.handleClear(this.route)
      }
    },
    handleEditClick () {
      let palnContent = this.$refs.planContent
      if (palnContent) {
        palnContent.handleEdit(this.route)
      }
    },
    onDeleteButtonClick () {
      if (!this.check()) {
        return false
      }
      let palnContent = this.$refs.planMenu
      if (palnContent) {
        palnContent.onDelete()
      }
    },
    handlePlanChart (routeData, patternList, greenwave, allPatternList) {
      let chartData = {
        routeData,
        patternList,
        greenwave,
        allPatternList
      }
      this.editableTabs[this.currentIndex].devs = routeData.devs
      this.chartData = chartData
    },
    handlePatternTable (routeData, patternList, phaseList) {
      this.isMenuDisabled = false
      let index = this.currentIndex
      let patterntable = this.$refs.patterntable[index]
      patterntable.onPatternTable(routeData, patternList, phaseList)
    },
    onNewPatternListChange (newPatternList) {
      let list = JSON.parse(JSON.stringify(newPatternList))
      let editableTab = this.editableTabs[this.currentIndex]
      let devs = editableTab.devs
      let devList = []
      for (let dev of devs) {
        for (let pattern of list) {
          if (dev.agentid === pattern.agentid) {
            dev = {...dev, ...pattern}
            // dev.fixedtimeplanType = 'flow-split-opt'
            dev.isused = pattern.isused
            let allPatterns = pattern.allPatterns
            for (let p of allPatterns) {
              if (p.id === dev.patternid) {
                p.cycle = dev.cycle
                p.offset = dev.offset
                if (p.contrloType === 'stage' || (p.stagesList && p.stagesList.length > 0)) {
                  p.rings = p.rings
                } else {
                  p.rings = dev.rings
                }
              }
            }
            dev.patternList = JSON.parse(JSON.stringify(allPatterns))
            if (dev.feature && dev.feature.patternList) {
              dev.feature.patternList = JSON.parse(JSON.stringify(allPatterns))
            } else {
              let feature = {
                patternList: JSON.parse(JSON.stringify(allPatterns))
              }
              dev.feature = feature
            }
            devList.push(dev)
          }
        }
      }
      editableTab.devs = devList
      if (!this.isShowOperation) {
        this.refreshChart()
      }
    },
    refreshChart () {
      let time = setTimeout(() => {
        // this.$refs.routeChart.refresh()
        this.onChartClick()
        clearTimeout(time)
      }, 500)
    },
    afterEnter () {
      if (this.chooseId === 0) {
        return false
      }
      let {routeData, patternList, greenwave, allPatternList} = {...this.chartData}
      this.$refs.routeChart.onPlanChart(routeData, patternList, greenwave, allPatternList)
    },
    onChartClick () {
      let routeData = this.editableTabs[this.currentIndex]
      const isCheckName = false
      const isCheckPlan = false
      const isCheckkeyintsid = false
      let check = this.checkData([routeData], isCheckName, isCheckPlan, isCheckkeyintsid)
      if (!check) {
        return false
      }
      this.getDeviceByIds(routeData)
    },
    onGenerateClick () {
      let routeData = this.editableTabs[this.currentIndex]
      // check
      let check = this.checkData([routeData], false)
      if (!check) {
        return false
      }
      let msg = this.$t('openatc.greenwaveoptimize.algorithmEngineOptimization')
      const loading = this.$loading({
        lock: true,
        text: msg,
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)'
      })
      setTimeout(() => {
        loading.close()
        this.handleGenerateClick(routeData)
      }, 1000)
    },
    handleGenerateClick (routeData) {
      let planContent = this.$refs.planContent
      planContent.handleCreate(routeData)
    },
    checkData (tabs, isCheckName = true, isCheckPlan = false, isCheckkeyintsid = true) {
      let res = true
      if (this.chooseId === 0) {
        this.$message.warning(this.$t('openatc.greenwaveoptimize.chooseRoute'))
        return false
      }
      for (let tab of tabs) {
        if (!tab.optstrategy) {
          this.$message.warning(this.$t('openatc.greenwaveoptimize.pleaseChoseOptstrategy'))
          return false
        }
        if (isCheckName && !tab.name) {
          this.$message.warning(this.$t('openatc.greenwaveoptimize.pleaseInputPatternName'))
          return false
        }
        let filterList = tabs.filter(item => item.name === tab.name)
        if (filterList.length > 1) {
          this.$message.warning(this.$t('openatc.greenwaveoptimize.repeatPatternName'))
          return false
        }
        if (isCheckkeyintsid && !tab.keyintsid) {
          this.$message.warning(this.$t('openatc.greenwaveoptimize.pleaseChoseKeyintersection'))
          return false
        }
        if (!tab.upspeed) {
          this.$message.warning(this.$t('openatc.greenwaveoptimize.pleaseInputUpspeed'))
          return false
        }
        if (!tab.downspeed) {
          this.$message.warning(this.$t('openatc.greenwaveoptimize.pleaseInputDownspeed'))
          return false
        }
        if (!tab.devs || tab.devs.length === 0) {
          this.$message.warning(this.$t('openatc.greenwaveoptimize.abnormalIntersections'))
          return false
        }
        if (isCheckPlan) {
          if (!tab.month) {
            this.$message.warning(this.$t('openatc.greenwaveoptimize.月份为空'))
            return false
          }
          if (!tab.month) {
            this.$message.warning(this.$t('openatc.greenwaveoptimize.周为空'))
            return false
          }
          if (!tab.month) {
            this.$message.warning(this.$t('openatc.greenwaveoptimize.日期为空'))
            return false
          }
          if (!tab.month) {
            this.$message.warning(this.$t('openatc.greenwaveoptimize.时段为空'))
            return false
          }
        }
        // reset date
        this.resetDate(tab)
      }
      return res
    },
    checkDownloadData (tabs, isCheckPlan = true) {
      let res = true
      if (this.chooseId === 0) {
        return false
      }
      for (let tab of tabs) {
        if (isCheckPlan) {
          if (!tab.month || tab.month.length === 0) {
            // this.$message.warning(this.$t('openatc.greenwaveoptimize.月份为空'))
            return false
          }
          if (!tab.day || tab.day.length === 0) {
            // this.$message.warning(this.$t('openatc.greenwaveoptimize.周为空'))
            return false
          }
          if (!tab.date || tab.date.length === 0) {
            // this.$message.warning(this.$t('openatc.greenwaveoptimize.日期为空'))
            return false
          }
          if (!tab.plan || tab.plan.start === '' || tab.plan.end === '') {
            // this.$message.warning(this.$t('openatc.greenwaveoptimize.时段为空'))
            return false
          }
        }
        // reset date
        this.resetDate(tab)
      }
      return res
    },
    onSaveClick () {
      // check
      let check = this.checkData(this.editableTabs)
      if (!check) {
        return false
      }
      let routeData = this.editableTabs
      let planContent = this.$refs.planContent
      planContent.handleSave(this.route.id, routeData)
    },
    onDownSendClick () {
      let routeData = this.editableTabs[this.currentIndex]
      let check = this.checkData([routeData])
      if (!check) {
        return false
      }
      this.resetDate(routeData)
      let planContent = this.$refs.planContent
      planContent.handleDownload(this.route.id, routeData)
    },
    onExecuteClick () {
      let routeData = this.editableTabs[this.currentIndex]
      let check = this.checkData([routeData])
      if (!check) {
        return false
      }
      this.resetDate(routeData)
      let planContent = this.$refs.planExecute
      planContent.onExecuteClick(this.route.id, routeData)
    },
    onDownloadClick () {
      let routeData = this.editableTabs[this.currentIndex]
      let check = this.checkDownloadData([routeData])
      if (!check) {
        this.$confirm(this.$t('openatc.greenwaveoptimize.downloadConfirmInfo'), this.$t('openatc.common.tipsmodaltitle'), {
          confirmButtonText: this.$t('openatc.button.OK'),
          cancelButtonText: this.$t('openatc.button.Cancel'),
          type: 'warning'
        }).then(() => {
          this.doDownload(routeData)
        })
      } else {
        this.doDownload(routeData)
      }
    },
    doDownload (routeData) {
      this.resetDate(routeData)
      let planExecute = this.$refs.planExecute
      planExecute.onDownloadClick(this.route.id, routeData, this.route.name)
    },
    async onDeleteClick (targetName) {
      let res = {
        checkFlag: false,
        doDeleteFlag: false
      }
      let routeData = this.editableTabs[this.currentIndex]
      // check
      let id = routeData.id
      if (targetName !== routeData.tabName) {
        this.$message.warning(this.$t('openatc.greenwaveoptimize.choosePattern'))
        return res
      }
      if (this.editableTabs.length === 1) {
        this.$message.warning(this.$t('openatc.greenwaveoptimize.atleastOnePattern'))
        return res
      }
      let optPatternList = this.route.optPatternList
      if (!optPatternList) {
        res.checkFlag = true
        return res
      }
      let list = optPatternList.filter(item => item.id === id)
      if (list.length === 0) {
        res.checkFlag = true
        return res
      } else {
        let planContent = this.$refs.planContent
        let param = {
          routeid: this.route.id,
          optpatternid: id
        }
        let flag = await planContent.handleDelete(param)
        res.checkFlag = true
        res.doDeleteFlag = flag
        return res
      }
    },
    updateRouteWithoutRefresh () {
      let routeData = this.editableTabs
      let planContent = this.$refs.planContent
      let param = planContent.getSaveParam(this.route.id, routeData)
      this.getAllPlan(param)
    },
    resetDate (tab) {
      let date = tab.date
      let day = tab.day
      let month = tab.month
      if (date && date.includes('全选')) {
        let index = date.indexOf('全选')
        date.splice(index, 1) // 排除全选选项
      } else if (date && date.includes('All')) {
        let index = date.indexOf('All')
        date.splice(index, 1) // 排除全选选项
      }
      if (day && day.includes(8)) {
        let index = day.indexOf(8)
        day.splice(index, 1) // 排除全选选项
      }
      if (month && month.includes(0)) {
        let index = month.indexOf(0)
        month.splice(index, 1) // 排除全选选项
      }
    },
    onConditionChange (item) {
      item.name = item.title
    },
    onOptstrategyChange (val) {
      if (this.chartData.patternList) {
        this.chartData.routeData.optstrategy = val
      }
    },
    onDirectionChange (val) {
      if (this.chartData.patternList) {
        this.chartData.routeData.direction = val
      }
    },
    onUpspeedChange (val) {
      if (this.chartData.patternList) {
        this.chartData.routeData.upspeed = val
      }
    },
    onDownspeedChange (val) {
      if (this.chartData.patternList) {
        this.chartData.routeData.downspeed = val
      }
    },
    handleMonth (val, index) {
      let allValues = []
      // 保留所有值
      for (let item of this.months) {
        allValues.push(item.value)
      }
      // 若是全部选择
      if (val.includes(0)) this.editableTabs[index].month = allValues
      // 取消全部选中，上次有，当前没有，表示取消全选
      if (this.oldOptions.includes(0) && !val.includes(0)) this.editableTabs[index].month = []
      // 点击非全部选中，需要排除全部选中，以及，当前点击的选项
      // 新老数据都有全部选中
      if (this.oldOptions.includes(0) && val.includes(0)) {
        let tempIndex = val.indexOf(0)
        val.splice(tempIndex, 1) // 排除全选选项
        this.editableTabs[index].month = val
      }
      // 全选未选，但是其他选项全部选上，则全选选上，上次和当前，都没有全选
      if (!this.oldOptions.includes(0) && !val.includes(0)) {
        if (val.length === allValues.length - 1) this.editableTabs[index].month = [0].concat(val)
      }
      this.oldOptions = this.editableTabs[index].month
    },
    handleDate (val, index) {
      let allValues = []
      // 保留所有值
      for (let item of this.dates) {
        allValues.push(item)
      }
      // 判断中英文
      if (this.$i18n.locale === 'en') {
        // 若是全部选择
        if (val.includes('All')) this.editableTabs[index].date = allValues
        // 取消全部选中，上次有，当前没有，表示取消全选
        if (this.oldOptions.includes('All') && !val.includes('All')) this.editableTabs[index].date = []
        // 点击非全部选中，需要排除全部选中，以及，当前点击的选项
        // 新老数据都有全部选中
        if (this.oldOptions.includes('All') && val.includes('All')) {
          let tempIndex = val.indexOf('All')
          val.splice(tempIndex, 1) // 排除全选选项
          this.editableTabs[index].date = val
        }
        // 全选未选，但是其他选项全部选上，则全选选上，上次和当前，都没有全选
        if (!this.oldOptions.includes('All') && !val.includes('All')) {
          if (val.length === allValues.length - 1) this.editableTabs[index].date = ['All'].concat(val)
        }
      } else if (this.$i18n.locale === 'zh') {
        // 若是全部选择
        if (val.includes('全选')) this.editableTabs[index].date = allValues
        // 取消全部选中，上次有，当前没有，表示取消全选
        if (this.oldOptions.includes('全选') && !val.includes('全选')) this.editableTabs[index].date = []
        // 点击非全部选中，需要排除全部选中，以及，当前点击的选项
        // 新老数据都有全部选中
        if (this.oldOptions.includes('全选') && val.includes('全选')) {
          let tempIndex = val.indexOf('全选')
          val.splice(tempIndex, 1) // 排除全选选项
          this.editableTabs[index].date = val
        }
        // 全选未选，但是其他选项全部选上，则全选选上，上次和当前，都没有全选
        if (!this.oldOptions.includes('全选') && !val.includes('全选')) {
          if (val.length === allValues.length - 1) this.editableTabs[index].date = ['全选'].concat(val)
        }
      }
      this.oldOptions = this.editableTabs[index].date
    },
    handleDateInit (val, status) {
      if (status) {
        this.oldOptions = val
      } else {
        this.oldOptions = []
      }
    },
    handleDay (val, index) {
      let allValues = []
      // 保留所有值
      for (let item of this.days) {
        allValues.push(item.value)
      }
      // 若是全部选择
      if (val.includes(8)) this.editableTabs[index].day = allValues
      // 取消全部选中，上次有，当前没有，表示取消全选
      if (this.oldOptions.includes(8) && !val.includes(8)) this.editableTabs[index].day = []
      // 点击非全部选中，需要排除全部选中，以及，当前点击的选项
      // 新老数据都有全部选中
      if (this.oldOptions.includes(8) && val.includes(8)) {
        let tempIndex = val.indexOf(8)
        val.splice(tempIndex, 1) // 排除全选选项
        this.editableTabs[index].day = val
      }
      // 全选未选，但是其他选项全部选上，则全选选上，上次和当前，都没有全选
      if (!this.oldOptions.includes(8) && !val.includes(8)) {
        if (val.length === allValues.length - 1) this.editableTabs[index].day = [8].concat(val)
      }
      this.oldOptions = this.editableTabs[index].day
    },
    onIntersectionSelectChange (val, index) {
      this.editableTabs[index].keyintsid = val
    },
    initOldOptions (val, status) {
      if (status) {
        this.oldOptions = val
      } else {
        this.oldOptions = []
      }
    },
    beforeLeave (currentName, oldName) {
      // var self = this // 重点，如果name是add，则什么都不触发
      if (currentName === 'add') {
        if (this.chooseId === 0) {
          this.$message.warning(this.$t('openatc.greenwaveoptimize.chooseRoute'))
          return false
        }
        if (!this.route || !this.route.id) {
          this.$message.warning(this.$t('openatc.greenwaveoptimize.routeDeviceNotOnline'))
          return false
        }
        this.addTab()
        return false
      }
      for (let i = 0; i < this.editableTabs.length; i++) {
        let tab = this.editableTabs[i]
        if (tab.tabName === currentName) {
          this.currentIndex = i
          break
        }
      }
      this.initPatternList(this.chooseId)
      this.editableTabsValue = currentName
    },
    addTab () {
      this.handleTabsEdit('', 'add')
    },
    async handleTabsEdit (targetName, action) {
      if (action === 'add') {
        let newTabName = Number(this.editableTabs[this.editableTabs.length - 1].tabName) + 1 + ''
        let tabObj = {
          id: this.currentIndex + 1,
          name: this.$t('openatc.greenwaveoptimize.optimizePattern') + ' ' + newTabName,
          title: this.$t('openatc.greenwaveoptimize.optimizePattern') + ' ' + newTabName,
          tabName: newTabName,
          content: 'New Tab content',
          patternid: 1,
          'month': this.defaultMonth,
          'day': this.defaultDay,
          'date': this.defaultDate,
          'plan': {
            'start': '08:00',
            'end': '09:30'
          },
          'optstrategy': 'green',
          'direction': 'up',
          'keyintsid': '',
          'upspeed': this.defaultSpeed,
          'downspeed': this.defaultSpeed,
          'devs': []
        }
        this.editableTabs.push(tabObj)
        this.editableTabsValue = newTabName
      } else if (action === 'remove') {
        let res = await this.onDeleteClick(targetName)
        if (!res.checkFlag) {
          return false
        }
        let tabs = this.editableTabs
        this.editableTabs = tabs.filter(tab => tab.tabName !== targetName)
        let newTabName = Number(this.editableTabs[this.editableTabs.length - 1].tabName) + ''
        this.editableTabsValue = newTabName
        if (res.doDeleteFlag) {
          // this.updateRouteWithoutRefresh()
        }
      }
    },
    refresh () {
      this.getAllPlan()
      let planContent = this.$refs.planContent
      if (planContent) {
        // planContent.closeInterval()
        // planContent.startInterval()
      }
    },
    editStart () {
      let planContent = this.$refs.planContent
      if (planContent && planContent.timer > 0) {
        planContent.closeInterval()
      }
    },
    maskChange (val) {
      // 控制两个蒙层下按钮的层级关系，并判断第二个蒙层显示的时机
      if (val) {
        this.step = false
        this.zIndexObj = {
          addZIndex: 99,
          editZIndex: 96
        }
      } else {
        this.step = true
        this.zIndexObj = {
          addZIndex: 96,
          editZIndex: 99
        }
      }
    },
    resetContentComponent (resRoute) {
      // 每次切换侧边栏方案时，重置销毁planContent组件
      // this.reset = false
      this.getAllPlan(resRoute)
    },
    clear (route) {
      this.resetTab(route)
    },
    getAllPlan (resRoute) {
      if (!resRoute) {
        this.loading = true
      }
      GetAllRoute().then(res => {
        if (!resRoute) {
          this.loading = false
        }
        if (!res.data.success) {
          this.$message.error(getMessageByCode(res.data.code, this.$i18n.locale))
          return
        }
        let list = res.data.data
        if (this.filter) {
          list = list.filter(item => item.name.includes(this.filter))
        }
        if (!this.isShowOperation) {
          if (this.routesList && this.routesList.length > 0) {
            const ids = this.routesList.map(item => item.id)
            list = list.filter(item => ids.includes(item.id))
          } else {
            list = []
          }
        }
        this.planData = list
        let id = 0
        if (resRoute) {
          id = resRoute.id
        } else {
          id = this.planData && this.planData[0].id
        }
        let planMenu = this.$refs.planMenu
        if (planMenu) {
          planMenu.chooseId = id
          planMenu.selectPlan(id)
        }
      })
    },
    resetTab (route) {
      this.editableTabs = [
        {
          title: this.$t('openatc.greenwaveoptimize.optimizePattern') + ' 1',
          id: 1,
          name: this.$t('openatc.greenwaveoptimize.optimizePattern') + ' 1',
          tabName: '1',
          content: 'Tab 1 content',
          patternid: 1,
          'month': this.defaultMonth,
          'day': this.defaultDay,
          'date': this.defaultDate,
          'plan': {
            'start': '08:00',
            'end': '09:30'
          },
          'optstrategy': 'green',
          'direction': 'up',
          'keyintsid': '',
          'upspeed': this.defaultSpeed,
          'downspeed': this.defaultSpeed,
          'devs': []
        }
      ]
      this.tabIndex = 1
      this.currentIndex = 0
      this.editableTabsValue = '1'
      if (route) {
        this.route = route
      } else {
        this.keyintsidOptions = []
        this.chartData = {}
        this.route = {}
      }
    },
    chooseRoute (id, route) {
      // reset data
      if (id !== this.chooseId) {
        this.isMenuDisabled = true
        this.resetTab()
      }
      if (route && route.optPatternList && route.optPatternList.length > 0) {
        let tabName = route.optPatternList[0].tabName
        if (tabName !== '1') {
          this.editableTabsValue = tabName
        }
      }
      this.chooseId = id
      this.route = route
      this.compatibility = route.compatibility
      let optPatternList = route.optPatternList
      if (optPatternList && optPatternList.length > 0) {
        this.editableTabs = JSON.parse(JSON.stringify(optPatternList))
      } else {
        this.editableTabs[0].devs = route.devs
      }
      this.tabIndex = this.editableTabs.length
      this.keyintsidOptions = route.devs.map(item => {
        return {
          label: item.name,
          value: item.agentid
        }
      })
      this.initPatternList(id)
    },
    initPatternList (id) {
      let index = this.currentIndex
      let editableTab = this.editableTabs[index]
      let planContent = this.$refs.planContent
      if (planContent) {
        if (editableTab.devs.length === 0) {
          let route = JSON.parse(JSON.stringify(this.route))
          route.name = editableTab.name
          route.upspeed = this.defaultSpeed
          route.downspeed = this.defaultSpeed
          editableTab = {...editableTab, ...route}
          editableTab.id = this.currentIndex + 1
        }
        editableTab.upspeed = editableTab.upspeed ? editableTab.upspeed : this.defaultSpeed
        editableTab.downspeed = editableTab.downspeed ? editableTab.downspeed : this.defaultSpeed
        if (this.editableTabs[index].devs.length === 0) {
          this.editableTabs[index] = editableTab
        }
        planContent.init(this.chooseId, editableTab)
      }
    },
    onErrorOcurrred () {
      this.isMenuDisabled = false
      this.resetTab(this.route)
      let patterntable = this.$refs.patterntable
      if (patterntable instanceof Array) {
        patterntable = patterntable[0]
      }
      patterntable.newPatternList = []
    },
    resetRoutePhaseId (rotueData) {
      for (let dev of rotueData.devs) {
        let pattern = dev.feature.patternList[0]
        if (pattern.rings.length === 0 || pattern.contrloType === 'stage') {
          this.resetDevPhaseId(dev, pattern)
        }
      }
    },
    resetDevPhaseId (routeData, targetPattern) {
      let forwardphaseid = routeData.forwardphaseid
      let backphaseid = routeData.backphaseid
      let targetForwardphaseid = -1
      let targetBackphaseid = -1
      let stagesList = targetPattern.stagesList
      for (let i = 0; i < stagesList.length; i++) {
        let stageItem = stagesList[i]
        if (targetForwardphaseid < 0 && stageItem.phases.includes(forwardphaseid)) {
          targetForwardphaseid = i + 1
        }
        if (targetBackphaseid < 0 && stageItem.phases.includes(backphaseid)) {
          targetBackphaseid = i + 1
        }
        if (targetForwardphaseid > 0 && targetBackphaseid > 0) {
          break
        }
      }
      routeData.forwardphaseid = targetForwardphaseid
      routeData.backphaseid = targetBackphaseid
    },
    async getDeviceByIds (routeData) {
      // 获取设备表格信息
      let realtimeRouteData = JSON.parse(JSON.stringify(routeData))
      this.deviceIds = realtimeRouteData.devs.map(ele => ele.agentid)
      // reset routeData phaseid
      // this.resetRoutePhaseId(realtimeRouteData)
      let greenWave = await this.$refs.planContent.getBandwidth(routeData)
      // console.log('greenWave:', greenWave)
      GetDeviceByIds(this.deviceIds).then(async res => {
        if (!res.data.success) {
          this.$message.error(getMessageByCode(res.data.code, this.$i18n.locale))
          return
        }
        this.devicesData = res.data.data
        // 取路口对应的实际方案id
        let devs = realtimeRouteData.devs
        for (let inter of devs) {
          inter.patternid = this.getActurlPatternid(inter.agentid)
          let devFeature = this.chartData.allPatternList.find(item => item.agentid === inter.agentid)
          // for (let pattern of devFeature.feature.patternList) {
          //   if (!pattern.rings || pattern.rings.length === 0) {
          //     let stagesList = pattern.stagesList
          //     if (stagesList && stagesList.length > 0) {
          //       let tempRings = stagesList.map((item, index) => {
          //         let ringItem = {
          //           id: index + 1,
          //           value: item.stageSplit
          //         }
          //         return ringItem
          //       })
          //       pattern.rings = [tempRings]
          //     }
          //   }
          // }
          inter.patternList = devFeature.feature.patternList
        }
        this.chartData.realPatternRouteData = realtimeRouteData
        this.chartData.routeId = this.chooseId
        let realtimeGreenWave = await this.$refs.planContent.getBandwidth(realtimeRouteData)
        // console.log('realtimeGreenWave', realtimeGreenWave)
        const greenWaveParam = this.getGreenWaveParam(greenWave, realtimeGreenWave)
        if (!this.isShowOperation) {
          let params = {
            routeId: this.chooseId,
            chartData: this.chartData,
            devicesData: this.devicesData,
            greenWaveParam: greenWaveParam
          }
          console.log('rimeDistanceChart params:', params)
          this.$refs.rimeDistanceChart.show(true, this.chartData, this.route.name, this.devicesData, greenWaveParam)
        } else {
          this.$refs.chartDialog.show(true, this.chartData, this.route.name, this.devicesData, greenWaveParam)
        }
        // 计算带宽
      })
    },
    getGreenWaveParam (greenWave, realtimeGreenWave) {
      let res = {}
      if (greenWave && realtimeGreenWave) {
        let up = greenWave.find(item => item.type === 'up')
        let down = greenWave.find(item => item.type === 'down')
        let realtimeUp = realtimeGreenWave.find(item => item.type === 'up')
        let realtimeDown = realtimeGreenWave.find(item => item.type === 'down')
        res = {
          greenWave: {
            up: up,
            down: down
          },
          realtimeGreenWave: {
            up: realtimeUp,
            down: realtimeDown
          }
        }
      }
      return res
    },
    getActurlPatternid (agentid) {
      let devinfo = this.devicesData.filter(dev => dev.agentid === agentid)[0]
      if (devinfo && devinfo.patternid !== undefined) {
        return devinfo.patternid
      } else {
        return 1
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.el-button--primary.is-plain:active{
  color: #fff;
}
.el-button--primary.is-plain:hover, .el-button--primary.is-plain:focus{
  color: #fff;
}
</style>
